import { type MockMethod } from "vite-plugin-mock";
import * as mockServer from "vite-plugin-mock/es/createProdMockServer";
import getBaseApis from "@/apis/base";
import getUsersApis from "@/apis/user";
import { createRestfulApis } from "@/create";
import { defaultDesignMap } from "./design";
import { CommonObj } from "@/types";
import { getDesignData } from "@/design/_utils";
import defaultFieldTpls from "@/design/tpls";

export type DesignMap = CommonObj;

export let allData: CommonObj = {};

// 生成 mock Api
function createMockApis(designMap: DesignMap) {
  allData = getDesignData(designMap); // 生成 mock 数据
  const restfulApis = Object.keys(designMap)
    .map((key: string) => createRestfulApis(key, allData))
    .flat(1);
  return [...getBaseApis(allData), ...getUsersApis(allData), ...restfulApis];
}

/**
 * 启动生产环境的 mock 服务
 * @param {object} designMap 表库设计对象数据
 * @param {object} fieldTpls 字段模板
 */
export function setupProdMockServer(
  designMap: DesignMap = defaultDesignMap,
  fieldTpls = defaultFieldTpls
) {
  const { createProdMockServer } = mockServer;
  if (designMap !== defaultDesignMap)
    Object.assign(defaultDesignMap, designMap);
  const apis = createMockApis(designMap);
  createProdMockServer(apis as MockMethod[]);
  if (fieldTpls !== defaultFieldTpls)
    Object.assign(defaultFieldTpls, fieldTpls);
  // 例：[{ method: "get", response: (req: any) => {}, url: "/get/opts" }];
  return apis;
}
